package megrez.common.core.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 文件名计数器
 * 
 * @author Lucky Yang
 * @since 0.0.1
 */
public class FileNameCounter {
    public static final String UNKNOW_FILE_NAME = "未知文件名";
    private Map<String, Integer> nameCache = new ConcurrentHashMap<>();

    /**
     * 如果有重复的文件名，生产带计数的文件名称
     * 
     * @param fileName
     * @return
     */
    public String count(final String fileName) {
        String fileNameTmp = fileName;
        if (fileNameTmp == null || fileName.trim().length() == 0) {
            fileNameTmp = UNKNOW_FILE_NAME;
        }
        if (!FileNameHelper.validate(fileNameTmp)) {
            throw new CommonRuntimeException("File name is incorrect: %s ", fileNameTmp);
        }

        nameCache.computeIfAbsent(fileNameTmp, key -> -1);
        Integer value = nameCache.computeIfPresent(fileNameTmp, (k, v) -> v + 1);

        if (value.intValue() > 0) {
            // 修改文件名称，增加计数到文件名
            final int index = fileNameTmp.indexOf(".");
            if (index < 0) {
                return fileNameTmp + " - " + value;
            }

            return String.format("%s - %s%s",
                    fileNameTmp.substring(0, index),
                    value,
                    fileNameTmp.substring(index));
        }
        return fileNameTmp;
    }
}
